package com.angus.auth.service.front;

import com.angus.api.front.RemoteFrontLogService;
import com.angus.api.front.domain.FrontLoginInfo;
import com.angus.common.core.constant.Constants;
import com.angus.common.core.constant.SecurityConstants;
import com.angus.common.core.utils.BrowserUtils;
import com.angus.common.core.utils.IpLocationUtils;
import com.angus.common.core.utils.StringUtils;
import com.angus.common.core.utils.TerminalUtils;
import com.angus.common.core.utils.ip.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 记录日志方法
 * 
 * @author ruoyi
 */
@Slf4j
@Component
public class FrontRecordLogService {
    @Resource
    private RemoteFrontLogService remoteLogService;

    /**
     * 记录登录信息
     * 
     * @param username 用户名
     * @param status 状态
     * @param message 消息内容
     * @return
     */
    public void recordLoginInfo(String username, String status, String message)
    {
        FrontLoginInfo loginInfo = new FrontLoginInfo();
        loginInfo.setUserName(username);
        loginInfo.setIpaddr(IpUtils.getIpAddr());
        loginInfo.setIpLocation(IpLocationUtils.getIpLocation(loginInfo.getIpaddr()));
        // 通过RequestContextHolder获取当前请求
        String terminalType = "Unknown";
        String browserType;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            terminalType = TerminalUtils.getTerminalType(request);
            browserType = BrowserUtils.getBrowserType(request);
            loginInfo.setBrowser(browserType);
        } catch (Exception e) {
            log.warn("获取终端设备类型失败: {}", e.getMessage());
        }
        loginInfo.setTerminal(terminalType);
        loginInfo.setMsg(message);
        // 日志状态
        if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
        {
            loginInfo.setStatus(Constants.LOGIN_SUCCESS_STATUS);
        }
        else if (Constants.LOGIN_FAIL.equals(status))
        {
            loginInfo.setStatus(Constants.LOGIN_FAIL_STATUS);
        }
        remoteLogService.saveLoginInfo(loginInfo, SecurityConstants.INNER);
    }
}
